package com.jhz.speedy.component.db;

import android.content.ContentValues;
import android.database.Cursor;

import java.util.List;

/**
 * 数据访问对象基类
 * Created by JunHeZ on 2017/7/12.
 */

public abstract class BaseDao<T> {
    protected DbHelper dbHelper;

    protected String CREATE_TABLE = " CREATE TABLE ";
    protected String INTEGER = " INTEGER ";
    protected String LONG = " LONG ";
    protected String INTEGER_P_KEY_AUTO = " INTEGER PRIMARY KEY AUTOINCREMENT ";
    protected String INTEGER_P_KEY = " INTEGER PRIMARY KEY ";
    protected String TEXT = " TEXT ";
    protected String COMMA = " , ";
    protected String START = " ( ";
    protected String END = " ) ";

    public BaseDao() {
        dbHelper = DbHelper.getInstance();
    }

    /**
     * @return 获取表名
     */
    public abstract String getTableName();

    /**
     * @return 获取主键
     */
    public abstract String getMajorKey();

    /**
     * 实例化
     */
    protected abstract T instance(Cursor cursor);

    /**
     * 实例转数据
     */
    protected abstract ContentValues entityToCV(T entity);

    /**
     * 获取创建语句
     */
    public abstract String getCreateStr();

    /**
     * 插入或更新
     *
     * @param entity     类型
     * @param majorValue 主键的值
     */
    public void insertOrUpdate(T entity, String majorValue) {
        ContentValues cv = entityToCV(entity);

        if (findByKey(getMajorKey(), majorValue) == null) {
            dbHelper.getWritableDatabase().insert(getTableName(), null, cv);
        } else {
            dbHelper.getWritableDatabase().update(getTableName(), cv, getMajorKey() + " = ? ", new String[]{majorValue});
        }
        dbHelper.close();
    }

    /**
     * 查找
     */
    public T findByKey(String key, String value) {
        T result = null;
        Cursor cursor = dbHelper.getReadableDatabase().query(getTableName(), null, key + " = ? ", new String[]{value}, null, null, null);
        if (cursor.moveToNext()) {
            result = instance(cursor);
        }
        cursor.close();
        return result;
    }

    /**
     * 查找所有
     *
     * @return
     */
    public List<T> findAll() {
        List<T> result = null;
        T entity;
        Cursor cursor = dbHelper.getReadableDatabase().query(getTableName(), null, null, null, null, null, null);
        if (cursor.moveToNext()) {
            entity = instance(cursor);
            result.add(entity);
        }
        cursor.close();
        return result;
    }


    /**
     * 删除所有
     */
    public void deleteAll() {
        dbHelper.getWritableDatabase().delete(getTableName(), null, null);
        dbHelper.close();
    }
}